/**
 * Created by forcht on 2018/5/20.
 */
public class Solution {
    int count=0;
    public int totalNQueens(int n) {
        dfs(0,n,new String[n]);
        return count;
    }
    void dfs(int cur,int n,String[] s) {
        if (cur >= n) count++;
        else {
            //判断是否会冲突
            for (int i = 0; i < n; i++) {
                boolean flag = false;
                for (int j = 0; j < cur && !flag; j++) {
                    for (int k = 0; k < n; k++) {
                        if (((cur + i == (j + k) || (cur - i) == (j - k) || (i == k)) && s[j].charAt(k) == 'Q')) {
                            flag = true;
                            break;
                        }
                    }
                }
                if (!flag) {
                    StringBuilder str = new StringBuilder();
                    for (int j = 0; j < n; j++) {
                        if (j == i) str.append("Q");
                        else str.append(".");
                    }
                    s[cur] = str.toString();
                    dfs(cur + 1, n, s);
                }
            }
        }
    }

    public static void main(String[] args) {
        Solution solution=new Solution();
        System.out.println(solution.totalNQueens(4));
    }
}
